<?php

class Controller_Admin_MailList extends Controller_Admin_Template
{
	private $pathAttachments = 'content/maillist/attachments/';
	private $maxSize = 5242880;

	public function before()
	{
		parent::before();
		$this->model = Model::factory('mailList');
	}

	public function actionIndex()
	{
		$this->addScript('/scripts/jquery/jquery.js');
		$this->addScript('/scripts/jquery/tablefilter/table.filter.js');
		$this->template->title = 'Subscribers management';
		$this->template->content = new View('admin/subscribers/list');
		$this->template->content->subscribers = $this->model->getSubscribers();
	}

	public function actionMessages()
	{
		$this->addScript('/scripts/jquery/jquery.js');
		$this->template->title = 'Messages';
		$this->template->content = new View('admin/subscribers/messages/list');
		$this->template->content->messages = $this->model->getMessages();
	}

	public function actionMessage($id = null)
	{
		if ($id) {
			if (!($message = $this->model->getMessages($id))) {
				throw new ForbiddenException('Message not found');
			}
		}
		$this->template->title = 'Compose a message';
		$this->template->content = new View('admin/subscribers/messages/compose');
		$form = new Form('message');
		$this->addScript('/scripts/jquery/jquery.js');
		$this->addScript('/scripts/jquery/jquery-ui.js');
		$this->addScript('/scripts/elrte/elrte.min.js');
		$this->addScript('/scripts/plugin/editor.js');
		$this->addLink(array(
			'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
			'rel'  => 'stylesheet',
			'type' => 'text/css',
		));
		$this->addLink(array(
			'href' => '/styles/elrte/elrte.full.css',
			'rel'  => 'stylesheet',
			'type' => 'text/css',
		));
		$form->text('subject', 'Subject')->attribute('size', 40)->rule('required')->bunched();
		$form->textarea('message', 'Message')->
			attribute('cols', 100)->
			attribute('rows', 15)->
			attribute('class', 'elrte')->
			rule('required')->
			callback('clearBr')->
			bunched();
		//$form->checkbox('copy', '', 'Send copy to my email');
		if ($id) {
			$this->template->content->messageId = $id;
			$form->loadValues($message);
		}
		$form->submit('submit', 'Continue to attachments')
			->attribute('class', 'awesome');
		function clearBr($field) {
			if ($field->value == '<br>') {
				$field->errors[] = 'This field is required';
			}
		}
		$this->template->content->form = $form;
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				if ($id) {
					$values = $form->getModified();
					Model_Table::instance('mailListMessages')->update($values, (int)$id);
					$this->response->redirect(Request::$controller . 'messages/');
				} else {
					$values = $form->getValues();
					$values['dateTime'] = date('Y-m-d H:i');
					$id = Model_Table::instance('mailListMessages')->insert($values);
					$this->response->redirect(Request::$controller . 'attachments/' . $id . '/');
				}
			}
		}
	}

	public function actionAttachments($id)
	{
		if (!($message = $this->model->getMessages($id))) {
			throw new ForbiddenException('Message not found');
		}
		$this->template->title = 'Attachments';
		$this->template->content = new View('admin/subscribers/messages/attachments');
		$attachments = $this->template->content->attachments = $this->model->getAttachments($id);
		$totalSize = 0;
		foreach ($attachments as $attachment) {
			$totalSize += $attachment['filesize'];
		}
		$this->template->content->pathAttachments = '/' . $this->pathAttachments;
		$this->template->content->totalSize = $totalSize;
		$this->template->content->maxSize = $this->maxSize;
		$this->template->content->messageId = $id;
		$form = new Form('file');
		$form->file('file', 'Attachment')
			->callback('checkSize', array(
				'totalSize' => $totalSize,
				'maxSize' => $this->maxSize,
			));
		function checkSize($field, $args) {
			extract($args);
			if (isset($field->files[0])) {
				$file = $field->files[0];
				if (($totalSize + $file['size']) > $maxSize) {
					$field->error(
						'Total size of your attachments must not exceed ' . number_format(($maxSize / (1024 * 1024)), 0, '.', '') . 'Mb<br />' .
						'With this attachment it will be ' . number_format((($totalSize + $file['size']) / (1024 * 1024)), 1, '.', '') . 'Mb'
					);
				}
			}
		}
		$this->template->content->form = $form;
		$form->submit('submit', 'Upload')
			->attribute('class', 'awesome');
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				$cnt = 0;
				while (true === Model_Table::instance('mailListAttachments')->exists(($alias = System::random('alphanuml', 3))) && $cnt < 3) {
					$cnt++;
				}
				if ($cnt == 3) {
					throw new ForbiddenException('Can\'t generate alias for attachment');
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$dir = $this->attachmentDir($id, $alias);
					if (!file_exists($dir)) {
						mkdir($dir, 0777, true);
					}
					$tmpFilename = $this->attachmentDir($id, $alias) . $file['name'];
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						throw new Exception('File %s cannot be moved.');
					}
					umask($umask);
					$filename = $file['name'];
					$filesize = filesize($tmpFilename);
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['messageId'] = $id;
					$values['filesize'] = $filesize;
					$values['filename'] = $filename;
					Model_Table::instance('mailListAttachments')->insert($values);
				} else {
					$form->error = 'File has not been uploaded.';
				}
				$this->response->redirect(Request::$controller . 'attachments/' . $id  . '/');
			}
		}

	}


	public function actionRecipients($id)
	{
		if (!($message = $this->model->getMessages($id))) {
			throw new ForbiddenException('Message not found');
		}
		$this->template->title = 'Recipients';
		$this->template->content = new View('admin/subscribers/messages/recipients');
		$this->template->content->messageId = $id;
		$recipients = array();
		foreach ($this->model->getRecipients($id) as $recipient) {
			$recipients[] = $recipient['subscriberId'];
		}
		$form = new Form('recipients');
		foreach (($subscribers = $this->template->content->recipients = $this->model->getSubscribers($id)) as $subscriber) {
			$form->checkbox('recipient-' . $subscriber['id'], '', $subscriber['name'], (in_array($subscriber['id'], $recipients)));
		}
		$this->template->content->form = $form;
		$form->submit('submit', 'Save')
			->attribute('class', 'awesome');
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				$values = $form->getValues();
				Database::instance()->query('DELETE FROM `mailListRecipients` WHERE `messageId` = ?', $id);
				foreach ($values as $recipientId => $value) {
					if ($value) {
						$recipient = array(
							'messageId' => $id,
							'subscriberId' => substr($recipientId, strpos($recipientId, '-') + 1)
						);
						Model_Table::instance('mailListRecipients')->insert($recipient);
					}
				}
				$this->response->redirect(Request::$controller . 'messages/');
			}
		}

	}

	public function actionSend($id)
	{
		if (!($message = $this->model->getMessages($id))) {
			throw new ForbiddenException('Message not found');
		}
		Model_Table::instance('mailListMessages')->update(array('status' => 'pending'), (int)$id);
		$this->response->redirect(Request::$controller . 'messages/');
	}

	public function actionAdd()
	{
		$this->template->title = 'Add subscriber';
		$this->actionEdit();
	}

	public function actionEdit($id = null)
	{
		if ($id) {
			$this->template->title = 'Edit subscriber profile';
			$form = new Form('subscriber');
		} else {
			$form = new Form('subscriber');
		}
		$form->attributes['autocomplete'] = 'off';
		$form->labelWidth = '150px';
		$form->text('name', 'Full name')->attribute('size', 32)
			->rule('maxLength', 64)->rule('required');
		$form->text('email', 'E-mail')->attribute('size', 32)
			->rule('maxLength', 64)->rule('email')->rule('required')
			->callback('emailCheck', array('id' => $id));
		function emailCheck($field, $args) {
			extract($args);
			Model_Table::instance('mailList')->keys['string'] = 'email';
			if (Model_Table::instance('mailList')->exists($field->value, $id)) {
				$field->error(Text::DUPLICATE_KEY);
			}
		}
		$form->checkbox('confirmed', '', 'Confirmed e-mail', 1);
		$form->checkbox('emailSubscriber', '', 'Send subscriber confirmation email');
		$form->submit('submit', 'Add');
		if ($id) {
			$form->elements['submit']->value = 'Save';
			$subscriber = $this->model->getSubscriber($id);
			$form->loadValues($subscriber);
		}
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				if ($id) {
					$values = $form->getModified();
					if (isset($values['emailSubscriber'])) {
						if ($values['emailSubscriber'] == 1) {
							MailList::getInstance()->sendConfirmation($id);
						}
						unset($values['emailSubscriber']);
					}
					Model_Table::instance('mailList')->update($values, $id);
				} else {
					$values = $form->getValues();
					$confirmation = false;
					if (isset($values['emailSubscriber'])) {
						if ($values['emailSubscriber'] == 1) {
							$confirmation = true;
						}
						unset($values['emailSubscriber']);
					}
					MailList::getInstance()->subscribe($values, $confirmation);
				}
				$this->response->redirect(Request::$controller);
			}
		}
		$this->template->content = new View('admin/subscribers/form', array('form' => $form));
	}

	public function actionRemove($id)
	{
		Model_Table::instance('mailList')->delete((int)$id);
		$this->response->redirect(Request::$controller);
	}

	public function actionRemoveAttachment($attachmentId, $internal = false)
	{
		$attachment = $this->model->getAttachment($attachmentId);
		$fileName = $this->attachmentPath($attachment['messageId'], $attachment['alias'], $attachment['filename']);
		if (file_exists($fileName)) {
			unlink($fileName);
			if (FileSystem::isDirEmpty($attDir = $this->attachmentDir($attachment['messageId'], $attachment['alias']))) {
				rmdir($attDir);
			}
			if (FileSystem::isDirEmpty($msgDir = $this->messageDir($attachment['messageId']))) {
				rmdir($msgDir);
			}
		}
		Model_Table::instance('mailListAttachments')->delete((int)$attachment['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'attachment/' . $attachment['messageId'] . '/');
		}
	}

	public function actionRemoveMessage($messageId, $internal = false)
	{
		if (!($message = $this->model->getMessages($messageId))) {
			throw new ForbiddenException('Message not found');
		}
		foreach (($attachments = $this->model->getAttachments($message['id'])) as $attachment) {
			$this->actionRemoveAttachment($attachment['id'], true);
		}
		Database::instance()->query('DELETE FROM `mailListRecipients` WHERE `messageId` = ?', $messageId);
		Model_Table::instance('mailListMessages')->delete((int)$messageId);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'messages/');
		}
	}

	private function attachmentPath($messageId, $alias, $filename)
	{
		return $this->pathAttachments . $messageId . '/' . $alias . '/' . $filename;
	}

	private function attachmentDir($messageId, $alias)
	{
		return $this->pathAttachments . $messageId . '/' . $alias . '/';
	}

	private function messageDir($messageId)
	{
		return $this->pathAttachments . $messageId . '/';
	}
}